import { getPeerCarDetail, getPeerImg, checkOuted, checkExpire } from '../../api/peerCar/index'
import { getWxAppConfig } from '../../api/wxAppConfig/index'
import { usingNature, energyNature } from '../../enums/car/index'
import { getToken, getUserInfo } from '../../utils/storage'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import config from "../../config/index"
import { checkPeer } from '../../api/wxuser/index'

Page({
  data: {
    carDetail: {} as ListPeerCar,
    user: {} as WxUser,
    panelShow: false,
    lockShow: false,
    callShow: false,
    lock: false,
    imgList: [] as PeerImg[],
    baseUrl: '',
    reduceCoin: 0,
    wxAppConfig: {} as ListWxAppConfig,
    outed: false,
    urls: [] as string[]
  },
  async initDetail(id: string) {
    const res = await getPeerCarDetail(id)
    const imgRes: any = await getPeerImg(id)
    const configRes = await getWxAppConfig()
    if(res.statusCode === config.SUCCESS_CODE) {
      let user = getUserInfo()
      let detail = res.data as ListPeerCar
      let usNature = usingNature.find(item => item.value === detail.usingNature) as nature
      let enNature = energyNature.find(item => item.value === detail.energy) as nature
      detail.usingNature = usNature.label
      detail.energy = enNature.label
      this.setData({
        carDetail: detail,
        user
      })
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
    if(imgRes.statusCode === config.SUCCESS_CODE) {
      let urls = [] as string[]
      imgRes.data.forEach((item: {id: string, peerId: string, url: string} ) => {
        urls.push(config.BaseUrl + '/' + item.url)
      });
      this.setData({
        imgList: imgRes.data,
        urls
      })
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
    if(configRes.statusCode === config.SUCCESS_CODE) {
      let user = getUserInfo()
      let wxAppConfig = configRes.data as ListWxAppConfig
      let reduceCoin: number
      if(user.userDiscount === 0) {
        reduceCoin = wxAppConfig.peerUseCoin
      } else {
        reduceCoin = Math.trunc(wxAppConfig.peerUseCoin * user.userDiscount / 100)
      }
      this.setData({
        reduceCoin,
        wxAppConfig
      })
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
  },
  //判断是否登录
  checkLogin() {
    if(!getToken()) {
      wx.showToast({
        title: '未登录',
        icon: 'error',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }, 1000)
        }
      })
    }
  },
  lock() {
    if(this.data.carDetail.isLock) {
      wx.showToast({title: '此车源已被锁定', icon: 'error'})
      return
    }
    //查看是否购买
    checkPeer(this.data.carDetail.id as string, this.data.user.id).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        if(res.data) {
          this.setData({
            lockShow: true
          })
        } else {
          //未购买提示先获取电话号码消耗积分
          Dialog.alert({
            title: '未获取电话号码',
            message: '请先点击获取电话按钮获取权益'
          }).then(() => {})
        }
      } else {
        wx.showToast({title: '网络错误', icon: 'error'})
      }
    })
  },
  toIndex() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  call() {
    //判断是否已经锁定
    if(this.data.carDetail.isLock && this.data.carDetail.lockWxUser !== this.data.user.id) {
      Dialog.alert({
        title: '已被他人锁定',
        message: `锁定时间为${this.data.carDetail.startLockDate}至${this.data.carDetail.endLockDate}`
      }).then(() => {})
      return
    }
    //判断是否已经购买过
    checkPeer(this.data.carDetail.id as string, this.data.user.id).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        //已经购买过，直接打电话
        if(res.data) {
          this.showPhone()
        } else {
          //判断现在积分是否足够购买
          if(this.data.reduceCoin > this.data.user.coin) {
            //不够就开启充值
            this.setData({
              panelShow: true
            })
            return
          }
          this.setData({
            callShow: true
          })
        }
      } else {
        wx.showToast({title: '网络错误', icon: 'error'})
      }
    })
  },
  showPhone() {
    Dialog.confirm({
      title: '联系电话为',
      message: this.data.carDetail.phone,
      confirmButtonText: '拨打电话'
    }).then(() => {
      wx.makePhoneCall({
        phoneNumber: this.data.carDetail.phone
      })
    }).catch(() => {})
  },
  onCallClose(e: any) {
    this.setData({
      callShow: e.detail,
    })
  },
  onClose(e: any) {
    this.setData({
      panelShow: e.detail
    })
  },
  onLockClose(e: any) {
    this.setData({
      lockShow: e.detail
    })
  },
  reLaunch() {
    wx.reLaunch({
      url: `/pages/peerCarDetail/peerCarDetail?id=${this.data.carDetail.id}`
    })
  },
  onLoad(e: any) {
    this.checkLogin()
    let id: string = e.id
    this.setData({
      baseUrl: config.BaseUrl
    })
    this.initDetail(id)
     //检查购买次数是否下架
     checkOuted(id).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        if(res.data) {
          this.setData({
            outed: true
          })
        } else {
          this.setData({
            outed: this.data.carDetail.outed
          })
        }
      }
    })
    //调用锁定人是否为用户
    if(this.data.carDetail.lockWxUser === this.data.user.id) {
      this.setData({
        lock: false
      })
      return
    }
   //检查锁定时间是否过期
    checkExpire(id).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        if(res.data) {
          this.initDetail(id)
          this.setData({
            lock: false
          })
        } else {
          this.setData({
            lock: this.data.carDetail.isLock
          })
        }
      }
    })
  },
  previewImg(e: any) {
    let url = e.currentTarget.dataset.url as string
    wx.previewImage({
      current: url,
      urls: this.data.urls
    })
  },
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: this.data.carDetail.brand + this.data.carDetail.carName
        })
      }, 1000)
    })
    return {
      title: this.data.carDetail.brand + this.data.carDetail.carName,
      path: `/page/peerCarDetail/peerCarDetail?id=${this.data.carDetail.id}`,
      promise 
    }
  }
})